Page({
  data: {
    goodsId: '',
    goodsName: '',
    goodsImage: '',
    points: 0,
    originalPrice: 0,
    userInfo: {},
    defaultAddress: null,
    isPointsSufficient: true // 新增：用于控制兑换按钮的可用性
  },

  onLoad(query) {
    console.log('order-confirm onLoad - 页面加载，参数:', query);
    
    // 获取商品信息参数
    const { goodsId, goodsName, goodsImage, points, originalPrice } = query;
    
    this.setData({
      goodsId,
      goodsName,
      goodsImage,
      points: parseInt(points) || 0,
      originalPrice: parseFloat(originalPrice) || 0
    });

    console.log('order-confirm onLoad - 设置商品信息完成:', {
      goodsId: this.data.goodsId,
      goodsName: this.data.goodsName,
      goodsImage: this.data.goodsImage,
      points: this.data.points,
      originalPrice: this.data.originalPrice
    });

    // 加载用户信息和默认地址
    this.loadUserInfo();
    this.loadDefaultAddress();
  },

  // 加载用户信息
  loadUserInfo() {
    const app = getApp();
    let userInfo = app.getUserInfo1() || app.globalData.userInfo || {};
    
    console.log('加载用户信息:', userInfo);
    
    // 处理积分字段映射
    if (userInfo.totalPoint !== undefined) {
      // 如果存在 totalPoint 字段，映射到 points
      userInfo = {
        ...userInfo,
        points: userInfo.totalPoint || 0
      };
    } else if (userInfo.points === undefined) {
      // 如果既没有 totalPoint 也没有 points，设置默认值
      userInfo = {
        ...userInfo,
        points: 0
      };
    }
    
    console.log('处理后的用户信息:', userInfo);
    
    this.setData({
      userInfo
    });
  },

  // 加载默认地址
  loadDefaultAddress() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    // 获取用户ID
    const userId = this.data.userInfo?.id || 901; // 默认使用901

    wx.request({
      url: `http://localhost:8080/point/address/user/${userId}`, // 使用新的接口
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('加载默认地址:', res);
        if (res.data.code === 200) {
          const addressList = res.data.data || [];
          
          // 取第一条数据作为默认地址
          if (addressList.length > 0) {
            const firstAddress = addressList[0];
            this.setData({
              defaultAddress: firstAddress
            });
          }
        } else {
          console.error('获取默认地址失败:', res.data.msg);
        }
      },
      fail: (err) => {
        console.error('获取默认地址失败', err);
      }
    });
  },

  // 选择地址
  onSelectAddress() {
    wx.navigateTo({
      url: '/my/pages/address-manage/address-manage'
    });
  },

  // 页面显示时刷新地址和用户信息
  onShow() {
    console.log('order-confirm onShow - 当前地址:', this.data.defaultAddress);
    
    // 刷新用户信息（确保积分数据是最新的）
    this.loadUserInfo();
    
    // 检查全局变量中是否有新选择的地址
    const app = getApp();
    if (app.globalData.selectedAddress) {
      console.log('order-confirm onShow - 发现全局变量中的新地址:', app.globalData.selectedAddress);
      this.setData({
        defaultAddress: app.globalData.selectedAddress
      });
      
      // 清除全局变量
      app.globalData.selectedAddress = null;
      
      // 显示地址更新提示
      wx.showToast({
        title: '地址已更新',
        icon: 'success'
      });
    } else {
      console.log('order-confirm onShow - 全局变量中没有新地址，加载默认地址');
      this.loadDefaultAddress();
    }
    
    // 检查积分是否足够
    this.checkPointsAndUpdateUI();
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  // 生成订单编号
  generateOrderSn() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    
    // 生成4位随机数
    const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    
    // 格式：EX + 年月日时分秒 + 4位随机数
    const orderSn = `EX${year}${month}${day}${hours}${minutes}${seconds}${randomNum}`;
    
    console.log('生成的订单编号:', orderSn);
    return orderSn;
  },

  // 确认兑换
  onConfirmExchange() {
    if (!this.data.defaultAddress) {
      wx.showToast({
        title: '请先选择收货地址',
        icon: 'none'
      });
      return;
    }

    // 检查积分是否足够
    if (!this.isPointsSufficient()) {
      wx.showToast({
        title: '积分不足，无法兑换',
        icon: 'none'
      });
      return;
    }

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '兑换中...',
      mask: true
    });

    // 准备请求数据 - 使用新的接口格式
    const requestData = {
      userId: this.data.userInfo.id,
      goodsId: this.data.goodsId,
      goodsName: this.data.goodsName,
      addressId: this.data.defaultAddress.id,
      point: this.data.points
    };

    console.log('准备发送兑换请求，数据:', requestData);

    // 使用新的接口创建兑换订单（包含积分扣减和流水记录）
    wx.request({
      url: 'http://localhost:8080/point/order/create',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          wx.showToast({
            title: '兑换成功',
            icon: 'success'
          });

          // 更新商品库存和销量
          this.updateGoodsStockAndSales();

          // 更新用户积分（全局）
          const app = getApp();
          if (app.globalData.userInfo) {
            app.globalData.userInfo.points = (app.globalData.userInfo.points || 0) - this.data.points;
          }
          if (app.globalData.userInfo1) {
            app.globalData.userInfo1.totalPoint = (app.globalData.userInfo1.totalPoint || 0) - this.data.points;
          }

          // 更新页面积分显示
          const currentPoints = this.getUserCurrentPoints();
          const newPoints = Math.max(0, currentPoints - this.data.points);
          
          this.setData({
            'userInfo.points': newPoints,
            'userInfo.totalPoint': newPoints
          });

          console.log('兑换成功后更新积分显示:', {
            消耗积分: this.data.points,
            原积分: currentPoints,
            新积分: newPoints,
            订单ID: res.data.data.id
          });

          // 跳转到兑换详情页
          const orderId = res.data.data.id;
          console.log('准备跳转到兑换详情页，订单ID:', orderId);
          
          if (orderId) {
            setTimeout(() => {
              wx.redirectTo({
                url: `/my/pages/exchange-detail/exchange-detail?orderId=${orderId}`
              });
            }, 1500);
          } else {
            console.error('订单ID为空，无法跳转');
            wx.showToast({
              title: '订单创建成功，但ID获取失败',
              icon: 'none'
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg || '兑换失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('兑换失败', err);
        wx.showToast({
          title: '兑换失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 接收从地址管理页面返回的地址更新
  onAddressSelected(address) {
    console.log('order-confirm: 接收到地址更新:', address);
    console.log('order-confirm: 更新前的地址:', this.data.defaultAddress);
    
    if (address) {
      this.setData({
        defaultAddress: address
      });
      
      console.log('order-confirm: 地址更新完成，新地址:', this.data.defaultAddress);
      
      // 显示地址更新提示
      wx.showToast({
        title: '地址已更新',
        icon: 'success'
      });
    } else {
      console.log('order-confirm: 接收到的地址为空');
    }
  },

  // 获取用户当前积分
  getUserCurrentPoints() {
    const { userInfo } = this.data;
    // 优先使用 points 字段，如果没有则使用 totalPoint
    return userInfo.points || userInfo.totalPoint || 0;
  },

  // 计算剩余积分
  calculateRemainingPoints() {
    const currentPoints = this.getUserCurrentPoints();
    const consumePoints = this.data.points || 0;
    return Math.max(0, currentPoints - consumePoints);
  },

  // 检查积分是否足够
  isPointsSufficient() {
    const currentPoints = this.getUserCurrentPoints();
    const consumePoints = this.data.points || 0;
    const isSufficient = currentPoints >= consumePoints;
    
    console.log('积分检查:', {
      当前积分: currentPoints,
      需要积分: consumePoints,
      是否足够: isSufficient
    });
    
    return isSufficient;
  },

  // 检查积分并更新UI状态
  checkPointsAndUpdateUI() {
    const isSufficient = this.isPointsSufficient();
    
    // 更新兑换按钮状态
    this.setData({
      isPointsSufficient: isSufficient
    });
    
    if (!isSufficient) {
      console.warn('积分不足，无法兑换');
    }
  },

  // 更新商品库存和销量
  updateGoodsStockAndSales() {
    const goodsId = this.data.goodsId;
    if (!goodsId) {
      console.error('商品ID不存在，无法更新库存');
      return;
    }

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      return;
    }

    wx.request({
      url: `http://localhost:8080/point/goods/update-stock-sales/${goodsId}`,
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          console.log('商品库存和销量更新成功');
        } else {
          console.error('商品库存和销量更新失败:', res.data.msg);
        }
      },
      fail: (err) => {
        console.error('商品库存和销量更新请求失败:', err);
      }
    });
  }
}); 